package service;

import entity.Goods;
import entity.User;
import util.Result;

import java.util.Arrays;

public class UserManagement {
    /**
     * 用户管理类
     */

    private User[] users = {};//默认对象数组
    private final int DEFAULT_CAPACITY = 10;//默认给10个长度
    private int size = 0;//保存已存放的元素的个数

    public UserManagement(){
        users = new User[DEFAULT_CAPACITY];
    }

    /**
     *向数组中插入用户
     */
    public Result addUser(User user){
        //判断是否需要扩容数组
        if (this.size + 1 > this.users.length){//判断当前数组能否容下user
            int old_capacity = this.users.length;//就数组的长度
            int newLength = old_capacity + (old_capacity / 2);//新的数组是旧数组的1.5倍
            this.users = Arrays.copyOf(this.users,newLength);
        }

        //遍历查看用户是否重复
        for (int i = 0; i < this.size; i++) {
            User u = this.users[i];
            if (u.getUserName().equals(user.getUserName())){
                Result result = new Result(1,"用户名重复，注册失败");
                return result;
            }
        }

        this.users[this.size++] = user;
        return Result.sceess();
    }

    public Result login(User user){
        //没必要遍历所有对象
        //只需要遍历user的所有对象
        for (int i = 0; i < this.size; i++) {
            User u = this.users[i];
            if(u.getUserName().equals(user.getUserName()) && u.getUserPassword().equals(user.getUserPassword())){
                if (u.getUserStatus() == 0){
                    return Result.sceess();
                }else if(u.getUserStatus() == 1){
                    return new Result(1,"用户已被禁用");
                }
            }
        }
        return new Result(1,"用户名或密码错误");
    }

}
